//
//  UserDataEditPhoto.m
//  Molian
//
//  Created by 胡津 on 15/4/9.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

// 照片个数限制
#define GALLERY_PHOTO_LIMIT_NUM 8

#import "UserDataEditPhoto.h"

@interface UserDataEditPhoto ()
@property (strong, nonatomic) AVFile *avatarFile;
@property (strong, nonatomic)UILabel *headLabel;//当前头像标签
@end

@implementation UserDataEditPhoto
{
    NSInteger delIndex;
    NSMutableArray *imageUrls;
    UIView *selfview;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

-(void)setUpPhotoView
{
    [selfview removeFromSuperview];
    imageUrls = [NSMutableArray array];
    selfview = [[UIView alloc]initWithFrame:self.bounds];
    [self addSubview:selfview];
    
    // 加载大图
    int photoNum = (int)[self.Gallery.images count];
    if (photoNum > 0) {
        int count;
        if (_photoEdit) {
            count = 8;
        }else{
            count = (int)[self.Gallery.images count];
            if (count>=8) {
                count = 8;
            }
            
        }
        for (int i = 0; i < count; i++) {
            int x = i % 4;  // 列数
            int y = i / 4;  // 行数
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((DeviceWidth/25) *(1+6 *x), 10+(10+DeviceWidth/5) *y, (DeviceWidth/5), (DeviceWidth/5))];
            [imageView setContentMode:UIViewContentModeScaleAspectFill];
            imageView.clipsToBounds = YES;
            imageView.tag = i;
            imageView.layer.cornerRadius = 7;
            imageView.userInteractionEnabled = YES;
            [selfview addSubview:imageView];
            
            if (i < [self.Gallery.images count]) {
                AVFile *photoFile = self.Gallery.images[i];
                if (photoFile == nil||photoFile == NULL||[photoFile isEqual: [NSNull null]]) {
                    break;
                }
                NSLog(@"aaa%@,%@",photoFile,photoFile.url);
                [imageUrls addObject:photoFile.url];
                // 加载缩略图
                __weak UserDataEditPhoto *weakSelf = self;
                [photoFile getThumbnail:YES width:600 height:600 withBlock:^(UIImage * image, NSError *error) {
                    if (!error) {
                        imageView.image = image;
                        
                        if (_photoEdit) {
                            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:weakSelf action:@selector(deletePhoto:)]];
                            MLUser *u = [MLUser currentUser];
                            AVFile *photo = weakSelf.Gallery.images[i];
                            
                            if([u.avatar.url isEqualToString: photo.url]){
                                UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height-20, imageView.bounds.size.width, 20)];
                                bView.backgroundColor = RGBA(0, 0, 0, 0.5);
                                [imageView addSubview:bView];
                                weakSelf.headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height-20, imageView.bounds.size.width, 20)];
                                weakSelf.headLabel.font = [UIFont fontWithName:FontName size:12];
                                weakSelf.headLabel.textAlignment = NSTextAlignmentCenter;
                                weakSelf.headLabel.textColor = [UIColor whiteColor];
                                weakSelf.headLabel.text = @"当前头像";
                                weakSelf.headLabel.adjustsFontSizeToFitWidth = YES;
                                [imageView addSubview:weakSelf.headLabel];
                            }
                        }else{
                            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:weakSelf action:@selector(ClickPhoto:)]];
                        }
                    }
                }];

            }else{
                imageView.image = [UIImage imageNamed:@"me_placeholder_ing"];
            }
        
        }
    }
    
    //如果是自己照片的话可以新增图片
    if (_photoEdit) {
        // 增加新的图片
        if (photoNum < GALLERY_PHOTO_LIMIT_NUM) {
            int x = photoNum % 4;
            int y = photoNum / 4;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((DeviceWidth/25) *(1+6 *x), 10+(10+DeviceWidth/5) *y, (DeviceWidth/5), (DeviceWidth/5))];
            // 增加点击图片添加新图的手势
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addPhoto)]];
            imageView.userInteractionEnabled = YES;
            [imageView setContentMode:UIViewContentModeScaleAspectFill];
            imageView.clipsToBounds = YES;
            imageView.layer.cornerRadius = 7;
            imageView.image = [UIImage imageNamed:@"me_placeholder_jia_ing"];
            [selfview addSubview:imageView];
            
        }

    }
    
}

-(void)addPhoto
{
    FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
    mediaPicker.mediaType = FSMediaTypePhoto;
    mediaPicker.editMode = FSEditModeStandard;
    mediaPicker.delegate = self;
    [mediaPicker showFromView:self];
    
}
//压缩图片
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
//    //创建一个图形上下文形象
//    UIGraphicsBeginImageContext(newSize);
//    // 告诉旧图片画在这个新的环境,所需的
//    // new size
//    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//    //获取上下文的新形象
//    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//    // 结束上下文
    
//    UIGraphicsEndImageContext();
    
   // return newImage;
    
    
    CGFloat width = CGImageGetWidth(image.CGImage);
    CGFloat height = CGImageGetHeight(image.CGImage);
    
    float verticalRadio = newSize.height*1.0/height;
    float horizontalRadio = newSize.width*1.0/width;
    
    float radio = 1;
    if(verticalRadio>1 && horizontalRadio>1)
    {
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
    }
    else
    {
        radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
    }
    
    width = width*radio;
    height = height*radio;
    
    int xPos = (newSize.width - width)/2;
    int yPos = (newSize.height-height)/2;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(newSize);
    //下面4行代码可以把图片背景变为黑色
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
     CGRect rect = CGRectMake(0.0f, 0.0f, newSize.width, newSize.height);
    CGContextFillRect(context, rect);
   
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(xPos, yPos, width, height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}
- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    UIImage* image;
        if(mediaPicker.editMode == FSEditModeStandard){
            image = mediaInfo.editedImage;
        }else {
             image = mediaInfo.originalImage;
        }
        CGSize size = CGSizeMake(600, 600);
            float kCompressionQuality = 0.3;
    
         image = [UserDataEditPhoto imageWithImageSimple:image scaledToSize:size];
            NSData *imgData = UIImageJPEGRepresentation(image, kCompressionQuality);
            // 后台上传照片
            AVFile *addPhoto = [AVFile fileWithName:@"photo.jpg" data:imgData];
            // 异步上传照片,上传成功之后再显示添加的照片
    __weak UserDataEditPhoto *weakSelf = self;
            [addPhoto saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                [HUD hideFromViewAnimated:YES];
                if (succeeded) {
                    if (weakSelf.Gallery.images.count == 0) {
                        NSData *imgData = UIImageJPEGRepresentation(image, kCompressionQuality);
                        weakSelf.avatarFile = [AVFile fileWithName:@"avatar.jpg" data:imgData];
                        [weakSelf.avatarFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                            [HUD hideFromViewAnimated:YES];
                            if (succeeded) {
                                NSLog(@"save avatar succeed");
                                
                                MLUser *currentUser = [MLUser currentUser];
                                currentUser.avatar = weakSelf.avatarFile;
                                NSString *nstr = [weakSelf.avatarFile getThumbnailURLWithScaleToFit:YES width:100 height:100 quality:100 format:@"png"];
                                
                                currentUser.subAvatar = nstr;
                                [currentUser saveInBackgroundWithBlock: ^(BOOL succeed, NSError *error){
                                    
                                }];
                            } else {
                                NSLog(@"save avatar failed");
                                [HUD Prompt:@"保存头像失败,请检查网络再重试"];
                                weakSelf.avatarFile = nil;
                            }
                            
                        }];
                        [HUD setOnViewWithTitle:nil animated:YES];
                    }
                    
                    NSMutableArray *galleryImgs = [NSMutableArray arrayWithArray:weakSelf.Gallery.images];
                    [galleryImgs addObject:addPhoto];
                    weakSelf.Gallery.images = galleryImgs;
                    [weakSelf.Gallery saveInBackground];
                    if ([weakSelf.delegate respondsToSelector:@selector(changePhone)]) {
                        [weakSelf.delegate changePhone];
                    }
                    // 重新加载
                    [weakSelf setUpPhotoView];
                    
                } else {
                    [HUD Prompt:@"上传图片失败,请重试"];
                    [HUD hideFromViewAnimated:YES];
                    return;
                }
                
            }];
            [HUD setOnViewWithTitle:nil animated:YES];

}
- (void)ClickPhoto:(UITapGestureRecognizer *)recognizer
{    
    RDImageViewerController *viewController = [[RDImageViewerController alloc] initWithImageHandler:^id (NSInteger pageIndex) {
        return [imageUrls objectAtIndex:pageIndex];
    }
    numberOfImages:imageUrls.count direction:RDPagingViewDirectionRight];
    viewController.showPageNumberHud = YES;
    viewController.landscapeMode = RDImageScrollViewResizeModeAspectFit;
    viewController.pageIndex = recognizer.view.tag;
    
    if ([self.delegate respondsToSelector:@selector(selfNavigationControllerPushVC:)]) {
        [self.delegate selfNavigationControllerPushVC:viewController];
    }
    
    
   // [self.addViewController.navigationController pushViewController:viewController animated:YES];
}


- (void)deletePhoto:(UILongPressGestureRecognizer *)recognizer {
    // 获取对应的删除对象,根据预先设置的tag判断删除对象
    UIView *delView = [recognizer view];
    delIndex = delView.tag;
    MLUser *u = [MLUser currentUser];
    AVFile *photo = self.Gallery.images[delIndex];
    
    if(![u.avatar.url isEqualToString: photo.url]){
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:@"删除照片"
                                                        otherButtonTitles:@"设为头像", nil];
        actionSheet.tag = 1989;
        [actionSheet showInView:self];
    }else {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"该照片为当前头像不可删除"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:nil, nil];
        [actionSheet showInView:self];
    }
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (1989 == actionSheet.tag) {
        // 点击取消,返回
        if (buttonIndex == actionSheet.cancelButtonIndex) {
            return;
        }else if (buttonIndex ==  actionSheet.destructiveButtonIndex){
            // NSLog(@"删除照片");
            NSArray *tmpImgs = self.Gallery.images;
            NSMutableArray *galleryImgs = [NSMutableArray arrayWithArray:self.Gallery.images];
            AVFile *delPhoto = galleryImgs[delIndex];
            if (galleryImgs&&galleryImgs.count) {
                [galleryImgs removeObjectAtIndex:delIndex];
            }
            self.Gallery.images = galleryImgs;
            __weak UserDataEditPhoto *weakSelf = self;
            [self.Gallery saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [HUD hideFromViewAnimated:YES];
                    // 异步删除文件
                    [delPhoto deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if ([weakSelf.delegate respondsToSelector:@selector(changePhone)]) {
                            [weakSelf.delegate changePhone];
                        }
                    }];
                    // 重新加载图片
                    [weakSelf setUpPhotoView];
                } else {
                    // 删除失败,恢复
                    weakSelf.Gallery.images = tmpImgs;
                    [HUD Prompt:@"删除失败,请检查网络再重试"];
                }
            }];
            [HUD setOnViewWithTitle:nil animated:YES];//
            return;
        }else if (buttonIndex == actionSheet.firstOtherButtonIndex){
            //  NSLog(@"设为头像");
            MLUser *u = [MLUser currentUser];
            AVFile *photo = self.Gallery.images[delIndex];
            u.avatar = photo;
            AVFile *file = [AVFile fileWithURL:photo.url];
            __weak UserDataEditPhoto *weakSelf = self;
            NSString *nstr = [file getThumbnailURLWithScaleToFit:YES width:100 height:100 quality:100 format:@"png"];
            
            u.subAvatar = nstr;
            [u saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                // 重新加载图片
                [u refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                    if (!error) {
                        [weakSelf setUpPhotoView];
                    }
                }];
                
                //更换头像,通知好友列表
                //发送透传
                [[ShareData shareData].firstView login];
                [[ShareData shareData].secondView login];
                [[ShareData shareData].thirdView  login];
                [Utils changeUserDataSendUsers];
            }];
            
            
//            [file getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
//                AVFile *nfile = [AVFile fileWithData:UIImageJPEGRepresentation(image, 1)];
//                
//                [nfile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//                    
//                }];
//                
//                
//            }];
            
        }
    }
    
}
- (void)dealloc
{
    self.delegate = nil;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
